<template>
  <div class="add-notice">
    <el-menu-item index="6" @click="setupMapInteraction">发布公告</el-menu-item>
    <el-dialog title="公告发布" @close="resetPublisher" v-model="showDialog" draggable>
      <div class="publisher-content">
        <section class="area-selector">
          <el-input v-model="searchTerm" placeholder="搜索区域/电话" clearable />
          <el-table :data="filteredAreas" border stripe height="250" size="small">
            <el-table-column prop="name" label="区域名称" sortable />
            <el-table-column prop="tel" label="联系电话" />
          </el-table>
        </section>
        <section class="content-editor">
          <h4>公告内容：</h4>
          <el-input
            v-model="noticeContent"
            placeholder="请输入公告内容"
            type="textarea"
            :rows="4"
            @keyup.enter="submitNotice"
          />
        </section>
      </div>

      <template #footer>
        <el-button @click="resetPublisher">取消</el-button>
        <el-button type="primary" @click="submitNotice">发布</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onBeforeUnmount, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useMapStore } from '@/stores/mapStore'

const mapStore = useMapStore()
const showDialog = ref(false)
const noticeContent = ref('')
const searchTerm = ref('')
const areasData = ref([])
const isDrawingActive = ref(false)

watch(isDrawingActive, (newVal) => {
  console.log('isDrawingActive changed:', newVal)
  console.log(mapStore.mapInstance.getInteractions().getArray().length)
})
/* watch(showDialog, (newVal) => {
  console.log('areasData', areasData.value)
}) */

// 地图交互相关
let drawInteraction = null
let tempVectorSource = null

// 表格数据过滤
const filteredAreas = computed(() => {
  const keywords = searchTerm.value.split(/\s+/).filter(Boolean)
  return keywords.length
    ? areasData.value.filter((item) =>
        keywords.every((k) => item.name.includes(k) || item.tel.includes(k)),
      )
    : areasData.value
})

// 初始化设置地图交互
const setupMapInteraction = () => {
  isDrawingActive.value = !isDrawingActive.value
  if (isDrawingActive.value) {
    // 开启绘图模式
    cleanupMap()
    setupTempLayer()
    setupDrawHandler()
  } else {
    // 关闭绘图模式
    cleanupMap()
    resetPublisher(true) // 仅重置发布器状态
  }
}

// 创建临时绘图图层
const setupTempLayer = () => {
  // 确保只创建一个临时图层
  const existingLayer = mapStore.mapInstance
    .getLayers()
    .getArray()
    .find((layer) => layer.get('name') === 'tempVectorLayer')

  if (!existingLayer) {
    tempVectorSource = new window.ol.source.Vector()
    const layer = new window.ol.layer.Vector({
      name: 'tempVectorLayer',
      source: tempVectorSource,
      zIndex: 9999,
    })
    mapStore.mapInstance.addLayer(layer)
  }
}

// 配置绘图交互
const setupDrawHandler = () => {
  cleanInteractions()
  drawInteraction = new window.ol.interaction.Draw({
    source: tempVectorSource,
    type: 'Polygon',
    style: new window.ol.style.Style({
      stroke: new window.ol.style.Stroke({
        color: 'rgba(255,0,0,0.8)',
        width: 2,
      }),
      fill: new window.ol.style.Fill({
        color: 'rgba(255,0,0,0.1)',
      }),
    }),
  })

  drawInteraction.on('drawend', handleDrawComplete)
  mapStore.mapInstance.addInteraction(drawInteraction)
}

// 处理绘图完成
const handleDrawComplete = async (e) => {
  const residentialLayer = mapStore.mapInstance
    .getLayers()
    .getArray()
    .find((layer) => layer.get('name') === '居民地')

  if (!residentialLayer) {
    ElMessage.error('未找到居民地数据')
    cleanupMap()
    return
  }

  areasData.value = []
  processIntersectedFeatures(residentialLayer, e.feature.getGeometry().getExtent())
  tempVectorSource.clear() // 立即清除绘图图形
  mapStore.mapInstance.render()

  // 根据是否找到区域决定是否显示对话框，自动准备下一次绘制
  if (areasData.value.length) {
    showDialog.value = true
  } else {
    ElMessage.warning('选定区域无居民地')
    tempVectorSource.getFeatures().forEach((f) => tempVectorSource.removeFeature(f))
    setupDrawHandler() // 重新激活绘图交互
  }
}

// 处理相交要素
const processIntersectedFeatures = (layer, extent) => {
  layer
    .getSource()
    .getFeatures()
    .forEach((feature) => {
      if (feature.getGeometry().intersectsExtent(extent)) {
        const props = feature.getProperties().values_
        areasData.value.push({
          name: props.name,
          tel: props.tel,
        })
      }
    })
}

// 提交公告
const submitNotice = async () => {
  if (!noticeContent.value.trim()) {
    return ElMessage.warning('请输入公告内容')
  }

  try {
    const { status } = await axios.post(
      'http://localhost:3001/addnotice',
      {
        noticeObj: { publishContent: noticeContent.value },
      },
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json',
        },
      },
    )

    if (status === 201) {
      ElMessage.success('发布成功')
      resetPublisher(true)
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败，请检查网络')
  }
}

// 重置状态
const resetPublisher = (keepDrawing = false) => {
  showDialog.value = false
  noticeContent.value = ''
  searchTerm.value = ''
  areasData.value = []

  // 仅当明确要求保持绘图时才不清除
  if (!keepDrawing) {
    if (tempVectorSource) tempVectorSource.clear()
  }
}

// 清理地图资源
const cleanupMap = () => {
  cleanInteractions()
  // 清理临时图层
  const tempLayer = mapStore.mapInstance
    .getLayers()
    .getArray()
    .find((layer) => layer.get('name') === 'tempVectorLayer')

  if (tempLayer) {
    mapStore.mapInstance.removeLayer(tempLayer)
    tempLayer.getSource()?.clear()
    tempLayer.dispose()
  }

  // 清理数据源
  if (tempVectorSource) {
    tempVectorSource.getFeatures().forEach((f) => tempVectorSource.removeFeature(f))
    tempVectorSource.clear()
    tempVectorSource.dispose()
    tempVectorSource = null
  }
}
const cleanInteractions = () => {
  if (drawInteraction) {
    mapStore.mapInstance.removeInteraction(drawInteraction)
    drawInteraction.dispose()
    drawInteraction = null
  }
  // 强制清除可能残留的交互
  const interactions = mapStore.mapInstance.getInteractions().getArray()
  interactions.forEach((interaction) => {
    if (interaction instanceof window.ol.interaction.Draw) {
      console.log('清理残留的绘图交互前', interaction)
      mapStore.mapInstance.removeInteraction(interaction)
      interaction.dispose()
      console.log('清理残留的绘图交互后', interaction)
    }
  })
}

onBeforeUnmount(() => {
  cleanupMap()
})
</script>

<style lang="scss" scoped>
.add-notice {
  .publisher-content {
    display: grid;
    gap: 25px;

    .area-selector {
      .el-input {
        margin-bottom: 10px;
      }
    }

    .content-editor {
      h4 {
        margin: 0 0 13px 0;
        font-size: 14px;
        color: #606266;
      }
    }
  }

  :deep(.el-textarea__inner) {
    resize: vertical; //仅垂直方向可缩放
  }
}
</style>
